﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using System.IO;
using Arcanum.Game.Client.Presentation.Views;
using GalaSoft.MvvmLight.Messaging;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight;

namespace Arcanum.Game.Client.Presentation.ViewModels
{
    public class ConsoleViewModel: ViewModelBase, IDisposable
    {
        public ConsoleViewModel()
        {
            Messenger.Default.Register<ConsoleViewArgs>(this, this.OnConsoleInitialized);
            this.ProcessInputCommand = new RelayCommand<string>(this.ProcessInput);
        }

        public void Dispose()
        {
            StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
            standardOutput.AutoFlush = true;
            Console.SetOut(standardOutput);
            Console.WriteLine("Now redirecting console output to the standard output.");
        }

        private string title;

        public string Title
        {
            get { return title; }
            set { title = value; }
        }

        public const string COMMAND_LINE_PROPERTY_NAME = "CommandLine";

        private string commandLine;

        public string CommandLine
        {
            get { return commandLine; }
            set
            {
                commandLine = value;
                RaisePropertyChanged(COMMAND_LINE_PROPERTY_NAME);
            }
        }

        public ICommand ProcessInputCommand { get; set; }

        private void OnConsoleInitialized(ConsoleViewArgs e)
        {
            // Instantiate the writer 
            TextWriter writer = new TextBoxStreamWriter(e.OutputTextBlock);
            // Redirect the out Console stream 
            Console.SetOut(writer);
            Console.WriteLine("Now redirecting console output to the {0} text box.", e.OutputTextBlock.Name);
        }

        private void ProcessInput(string scriptText)
        {
            if (!string.IsNullOrEmpty(scriptText) && !string.IsNullOrWhiteSpace(scriptText)) {
                Console.WriteLine(scriptText);
                this.CommandLine = "";
            }
        }
    }
}
